﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.IO;
using System.Json;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Globalization;
using anael.Data;
using anael.ClientUtilities;
using anael.Model;
using System.Text;
using System.Threading;
using System.ComponentModel;

namespace anael
{


    public partial class Home : Page
    {

        public static ManualResetEvent allDone = new ManualResetEvent(false);
        const int BUFFER_SIZE = 1024;
        const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
        public string access_token { get; set; }

        // Abort the request if the timer fires.
        private static void TimeoutCallback(object state, bool timedOut)
        {
            if (timedOut)
            {
                HttpWebRequest request = state as HttpWebRequest;
                if (request != null)
                {
                    request.Abort();
                }
            }
        }

        public Home()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void fbLogin_Click(object sender, RoutedEventArgs e)
        {
            if (App.Current.IsRunningOutOfBrowser)
            {
                webBrowser1.Visibility = System.Windows.Visibility.Visible;
                webBrowser1.ScriptNotify += new EventHandler<NotifyEventArgs>(webBrowser1_ScriptNotify);
                webBrowser1.Navigate(new Uri("https://graph.facebook.com/oauth/authorize?client_id=173939665969932&redirect_uri=http://localhost:5857/FacebookConnect.htm&type=user_agent&display=popup&scope=email"));
            }
            else
            {
                HtmlPage.RegisterScriptableObject("FacebookHelper", this);
                HtmlPage.Window.Invoke("InitFacebook", "fr_FR");
            }
        }

        void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
        {
            Uri uri = new Uri(e.Value);
            string queryString = uri.Fragment;
            string[] values = queryString.Split('&');
            access_token = values[0].Substring(14);
            FacebookLoginCallback(access_token);
        }

        [ScriptableMember]
        public void FacebookLoginCallback(string accessToken)
        {
            if (!App.Current.IsRunningOutOfBrowser)
                this.access_token = accessToken;
            WebClient GetInfosUserWebClient = new WebClient();
            GetInfosUserWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetInfosUserWebClient_DownloadStringCompleted);
            Uri uri = new Uri("https://graph.facebook.com/me/?access_token=" + accessToken);
            GetInfosUserWebClient.DownloadStringAsync(uri);


            Uri uriFriendList = new Uri("https://graph.facebook.com/me/friends?access_token=" + accessToken);
            WebClient GetFriendListWebClient = new WebClient();
            GetFriendListWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetFriendListWebClient_DownloadStringCompleted);
            GetFriendListWebClient.DownloadStringAsync(uriFriendList);
        }

        private void GetFriendListWebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            TextReader text = new StringReader(e.Result);
            JsonObject resultjson = (JsonObject)JsonObject.Load(text);

            List<Friend> model = new List<Friend>();

            foreach (JsonObject friend in (JsonArray)resultjson["data"])
            {
                model.Add(Parser.ParseFriend(friend));
            }

            SessionInfo.ConnectedUser.Friends = model;

            this.friendList.ItemsSource = SessionInfo.ConnectedUser.Friends;

            foreach (Friend friend in SessionInfo.ConnectedUser.Friends)
            {
                LoadFBPicture("https://graph.facebook.com/" + friend.Id + "/picture", friend.Id);
            }

        }

        private void GetInfosUserWebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            TextReader text = new StringReader(e.Result);
            JsonObject resultjson = (JsonObject)JsonObject.Load(text);

            SessionInfo.ConnectedUser = Parser.ParseUser(resultjson);


            //LoadFBPicture("https://graph.facebook.com/" + SessionInfo.ConnectedUser.Id + "/picture", SessionInfo.ConnectedUser.Id);
        }


        private void LoadFBPicture(string url, string objectId)
        {
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            RequestState myRequestState = new RequestState();
            myRequestState.request = myHttpWebRequest;
            myRequestState.ObjectId = objectId;

            IAsyncResult result = (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
        }


        private void RespCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                // State of request is asynchronous.
                RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
                HttpWebRequest myHttpWebRequest = myRequestState.request;
                myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult);

                // Read the response into a Stream object.
                Stream responseStream = myRequestState.response.GetResponseStream();
                myRequestState.streamResponse = responseStream;

                anael.ClientUtilities.SmartDispatcher.BeginInvoke(() =>
                    {
                        try
                        {
                            BitmapImage im = new BitmapImage();
                            im.SetSource(responseStream);
                            SessionInfo.ConnectedUser.Friends.SingleOrDefault(element => element.Id == myRequestState.ObjectId).Image = im;
                        }
                        catch
                        { 
                        
                        }
                    });

            }
            catch 
            {

            }
        }

        private void friendList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            var toto = SessionInfo.ConnectedUser.Friends[2].Id;

            WebClient GetChildUserWebClient = new WebClient();
            GetChildUserWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetChildUserWebClient_DownloadStringCompleted);
            Uri uri = new Uri("https://graph.facebook.com/" + toto + "/photos?access_token=" + this.access_token);
            GetChildUserWebClient.DownloadStringAsync(uri);

        }



        private void GetChildUserWebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            TextReader text = new StringReader(e.Result);
            JsonObject resultjson = (JsonObject)JsonObject.Load(text);

            var toto = Parser.ParseUser(resultjson);
        }

    
    }


    public class ImageFromFBUriConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            BitmapImage bitmapimage = new BitmapImage(new Uri(value.ToString(), UriKind.Absolute));
            return bitmapimage;
        }



        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }

    }




    public class RequestState
    {
        // This class stores the State of the request.
        const int BUFFER_SIZE = 1024;
        public StringBuilder requestData;
        public byte[] BufferRead;
        public HttpWebRequest request;
        public HttpWebResponse response;
        public Stream streamResponse;
        public string ObjectId;


        public RequestState()
        {
            BufferRead = new byte[BUFFER_SIZE];
            requestData = new StringBuilder("");
            request = null;
            streamResponse = null;
            ObjectId = null;
        }
    }


}